// pages/user/user-address-list-page.js
import { RequestManager } from '../../util/requestManager.js'
let requestManager = new RequestManager()
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isPhoneX: false,
    isSelected:false,
    addressItems: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var title = "收货地址";
    if (typeof (options.selected) != "undefined") {
      title = "选择收货地址";
      this.setData({
        isSelected:true
      })
    }

    this.setData({
      isPhoneX: app.globalData.isIphoneX
    })

    wx.setNavigationBarTitle({
      title: title,
    })


    this.private_downloadData()
  },

  //  获取数据
  private_downloadData: function () {

    var that = this;
    requestManager.getUserAddressList(app.globalData.openid,(reslut)=>{
      that.setData({
        addressItems: reslut
      })
    });
  },
  //  添加地址
  action_add: function () {
    // wx.navigateTo({
    //   url: '/pages/edit/address-edit-page',
    // })
    wx.chooseAddress({
      success(res) {
        console.log(res.userName)
        console.log(res.postalCode)
        console.log(res.provinceName)
        console.log(res.cityName)
        console.log(res.countyName)
        console.log(res.detailInfo)
        console.log(res.nationalCode)
        console.log(res.telNumber)

        // name, province, city, address, phone, callback

        requestManager.addAddressItemToWeb(res.userName,res.provinceName,res.cityName,res.countyName + res.detailInfo,res.telNumber,success=>{
          
        });
      }
    })
  },
  //  编辑地址
  action_edit: function (event) {
    let editItem = event.detail
    wx.navigateTo({
      url: '/pages/edit/address-edit-page?dataItem=' + JSON.stringify(editItem),
    })
  },
  //  选择了收货地址
  action_selected:function(event){

    let is_selected = event.detail.checked;
    let key = event.detail.key;

    var tmpItems = this.data.addressItems;

    tmpItems.forEach((tmpItem) => {
      if (tmpItem.id === parseInt(key)) {
        tmpItem.selected = is_selected;
      }
      else {
        tmpItem.selected = false;
      }
    })
    this.setData({
      addressItems: tmpItems
    })
  },
  //  保存事件
  action_save:function(event){

    var selectedItem = null;
    var tmpItems = this.data.addressItems;
    tmpItems.forEach((tmpItem) => {
      if (tmpItem.selected) {
        selectedItem = tmpItem;
      }
    })

    console.log(tmpItems);

    if (selectedItem == null) {
      wx.showToast({
        title: "所选的收货地址不能为空",
        icon: 'none'
      });
      return;
    }


    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.setData({
      addressItem: selectedItem
    })

    wx.navigateBack({
      delta: 1
    })
  }
})